package com.enjoy.concurrent.ch1.pool;

import java.sql.Connection;
import java.util.LinkedList;
import java.util.Queue;

public class DBPool {

    private final Queue<Connection> pool = new LinkedList<>();

    public DBPool(int size) {
        for (int i = 0; i < size; i++) {
            pool.add(SqlConnectionImpl.fetchConnection());
        }
    }

    void releaseConnection(Connection connection) {
        if (connection != null) {
            synchronized (pool) {
                pool.add(connection);
                pool.notifyAll();
            }
        }
    }

    Connection fetchConnection(long mills) throws InterruptedException {
        synchronized (pool) {
            if (mills <= 0) {
                while (pool.isEmpty()) {
                    pool.wait();
                }
                return pool.remove();

            } else {
                // 超时时长
                long future = System.currentTimeMillis() + mills;
                // 等待时长
                long remaining = mills;
                while ((pool.isEmpty() && remaining > 0)) {
                    pool.wait(remaining);

                    // 唤醒一次
                    remaining = future - System.currentTimeMillis();
                }
                Connection connection = null;
                if (!pool.isEmpty()) {
                    connection = pool.remove();
                }
                return connection;
            }
        }
    }
}
